package artid.com.arttogo.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;

import artid.com.arttogo.R;


public class AudioService extends Service implements OnCompletionListener {
    MediaPlayer player = null;
    private final IBinder binder = new AudioBinder();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return binder;
    }

    @Override
    public void onCompletion(MediaPlayer player) {
        // TODO Auto-generated method stub
        player.start();// 结束了，则结束Service
    }

    // 在这里我们需要实例化MediaPlayer对象
    public void onCreate() {
        super.onCreate();
        // 我们从raw文件夹中获取一个应用自带的mp3文件
        setMusic(intmusic);
    }

    /**
     * 该方法在SDK2.0才开始有的，替代原来的onStart方法
     */
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!player.isPlaying()) {
            player.start();
        }
        return START_STICKY;
    }

    public void pauseMusic() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

    public void resumeMusic() {
        player.start();
    }

    public void onDestroy() {
        // super.onDestroy();
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();
    }

    public void setMusic(int i) {
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
        }

        switch (i) {
            case 0:
                player = MediaPlayer.create(this, R.raw.boatsong);
                player.setOnCompletionListener(this);
                break;
            case 1:
                player = MediaPlayer.create(this, R.raw.flower);
                player.setOnCompletionListener(this);
                break;
            case 2:
                player = MediaPlayer.create(this, R.raw.waterroad);
                player.setOnCompletionListener(this);
                break;
            default:
                break;
        }
        if (!player.isPlaying()) {
            player.start();
        }
    }

    int intmusic = 0;

    public class AudioBinder extends Binder {

        // 返回Service对象
        public AudioService getService(int i) {
            intmusic = i;
            return AudioService.this;
        }
    }
}
